package fr.isima.gui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import fr.isima.R;
import fr.isima.data.TrackProviderAdapter;
import fr.isima.model.Track;

public class TrackSelection extends Activity
{
    private static final String  TAG            = "TrackSelection";

    private TrackProviderAdapter providerAdpt;

    private TrackArrayAdapter    arrayAdpt;

    private ArrayList<Track>     arrayTrack;

    private ListView             listTrack;

    public static final String   TRACK_ID       = "TRACK_ID";

    // Menu
    static final private int     SORT_BY_NAME   = Menu.FIRST;

    static final private int     SORT_BY_DATE   = Menu.FIRST + 1;

    static final private int     DELETE_ALL     = Menu.FIRST + 2;

    // Dialog
    private static final int     CONFIRM_DIALOG = 1;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.track_selection);

        providerAdpt = new TrackProviderAdapter(getContentResolver());

        arrayTrack = new ArrayList<Track>();

        // Binding Data to View
        arrayAdpt = new TrackArrayAdapter(this, R.layout.track_item, arrayTrack);
        listTrack = (ListView) findViewById(R.id.allTracks);
        listTrack.setAdapter(arrayAdpt);

        // Handle the click on an item
        listTrack.setOnItemClickListener(new OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> adpt, View view, int index,
                    long arg3)
            {
                Track selected = arrayTrack.get(index);
                Intent details = new Intent(view.getContext(),
                        TrackDetails.class);
                details.putExtra(TRACK_ID, selected.getId());
                startActivity(details);
            }
        });

        updateArray(null);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);

        if(isTracksSaved())
        {
        MenuItem itemSortByName = menu.add(0, SORT_BY_NAME, Menu.NONE,
                R.string.sort_by_name);
        MenuItem itemSortByDate = menu.add(0, SORT_BY_DATE, Menu.NONE,
                R.string.sort_by_date);

        MenuItem itemDeleteAll = menu.add(0, DELETE_ALL, Menu.NONE,
                R.string.delete_all);

        itemSortByName.setShortcut('0', 'n');
        itemSortByDate.setShortcut('1', 'd');
        itemDeleteAll.setShortcut('2', 'r');
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case SORT_BY_DATE:
                updateArray(providerAdpt.getAllTracksSortedByDate());
                break;

            case DELETE_ALL:
                showDialog(CONFIRM_DIALOG);
                break;

            default:
                updateArray(providerAdpt.getAllTracksSortedByName());
                break;
        }
        return true;
    }

    private boolean isTracksSaved()
    {
        return providerAdpt.getAllTracksSortedByName().size() > 0;
    }
    private void deleteAllTracks()
    {
        providerAdpt.deleteAllTracks();
        updateArray(null);
        Log.d(TAG, "All tracks has been deleted");
    }

    private void updateArray(List<Track> loaded)
    {
        arrayTrack.clear();
        arrayAdpt.clear();

        if (loaded == null)
        {
            loaded = providerAdpt.getAllTracksSortedByName();
        }

        for (Track track : loaded)
        {
            arrayTrack.add(track);
            arrayAdpt.notifyDataSetChanged();
        }
        arrayAdpt.notifyDataSetChanged();

        Log.d(TAG, "Array Updated");

        if (arrayTrack.isEmpty())
        {
            TextView txt = new TextView(this);
            txt.setText(getResources().getString(R.string.no_tracks_saved));
            addContentView(txt, new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
        }

    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        AlertDialog alert = null;
        switch (id)
        {
            case CONFIRM_DIALOG:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                
                String yes = getResources().getString(R.string.yes);
                String no = getResources().getString(R.string.no);
                builder.setTitle(getResources().getString(R.string.confirm_delete_all_title));
                builder.setMessage("");
                builder.setCancelable(false).setPositiveButton(yes,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                deleteAllTracks();
                            }
                        }).setNegativeButton(no,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                dialog.cancel();
                            }
                        });
                alert = builder.create();
                yes = null;
                no = null;
                break;

            default:
                break;
        }
        return alert;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog)
    {
        switch (id)
        {
            case CONFIRM_DIALOG:
               int nbTracks = arrayTrack.size();
               String format = getResources().getString(R.string.confirm_delete_all);
               String message = String.format(format, nbTracks);
               
               AlertDialog confirmDialog = (AlertDialog) dialog;
               confirmDialog.setMessage(message);
               
               message = null;
               format = null;
                break;

            }
    }
}
